//
//  JCTextView.swift
//  SinaWeibo_18
//
//  Created by apple on 15/10/26.
//  Copyright © 2015年 cz. All rights reserved.
//

import UIKit

class JCTextView: UITextView {

    var placeholderText: String? {
        didSet{
            //设置占位文字内容
            placeholder.text = placeholderText ?? ""
        }
    }
    
    var placeholderFont: UIFont? {
        didSet{
            //设置占位文字的字体大小
            placeholder.font = placeholderFont
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        addSubview(placeholder)
        
        //注册通知观察者  监听键盘弹出的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textViewDidChange:", name: UITextViewTextDidChangeNotification, object: nil)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //  MARK: - textViewDelegate

    func textViewDidChange(notifi: NSNotification){
        //有文字 隐藏
        placeholder.hidden = self.hasText()
    }
    
    //占位文字的label
    private lazy var placeholder: UILabel = {
            let label = UILabel()
        label.numberOfLines = 0
//        label.textAlignment = NSTextAlignment.Center
        label.font = UIFont.systemFontOfSize(12)
//        label.text = "听说下雨天音乐和辣条更配哟~"
        label.textColor = UIColor.lightGrayColor()
        return label
        }()
    
    override func layoutSubviews() {
        super.layoutSubviews()
        placeholder.x = 5
        placeholder.y = 8
        placeholder.size = (placeholder.text ?? "").size(placeholder.font, constraintedToSize: CGSizeMake(width - placeholder.x*2, CGFloat(MAXFLOAT)))
    }
    //移除通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}
